import re
from django.contrib.auth.backends import ModelBackend
import logging
from qiniu import Auth, put_data
from users.models import User

from itsdangerous import TimedJSONWebSignatureSerializer, BadData
from mlh.settings import dev
from users import constants


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


# 预留多种授权方式
def get_user_by_account(account):
    """
    根据帐号获取user对象
    :param account: 手机号
    :return: User对象 或者 None
    """
    try:
        # 帐号为手机号
        if re.match('^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        elif re.match('^[a-zA-Z0-9_]{4,20}@(163|126|qq|sina|yahoo)\.com$', account):
            user = User.objects.get(email=account)
        else:
            return None
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """
    自定义用户名或手机号认证
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user is not None and user.check_password(password):
            return user


# 七牛云存储
# -*- coding: utf-8 -*-
# 需要填写你的 Access Key 和 Secret Key
access_key = 'lN9h_mk5hA5k4drxepQFhhLcCxu5Ht-x4jqQd82-'
secret_key = 'c7uK0bs96L8TBgv2CyJSZhnkUytsW-vIDRL2pEh-'

# 要上传的空间
bucket_name = 'avatar_url'


def storage(data):
    """七牛云存储上传文件接口"""
    if not data:
        return None
    try:
        # 构建鉴权对象
        q = Auth(access_key, secret_key)

        # 生成上传 Token，可以指定过期时间等
        token = q.upload_token(bucket_name)

        # 上传文件
        ret, info = put_data(token, None, data)

    except Exception as e:
        logging.error(e)
        raise e

    if info and info.status_code != 200:
        raise Exception("上传文件到七牛失败")

    # 返回七牛中保存的图片名，这个图片名也是访问七牛获取图片的路径
    return ret["key"]


if __name__ == '__main__':
    file_name = input("输入上传的文件")
    with open(file_name, "rb") as f:
        storage(f.read())


def generate_verify_email_url(data):
    """
    生成验证邮箱的url
    """
    serializer = TimedJSONWebSignatureSerializer(dev.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    token = serializer.dumps(data).decode()
    verify_url = 'http://www.mlh.site:8080/success_verify_email.html?token=' + token
    return verify_url


def check_verify_email_token(token):
    """检查验证邮件的token"""
    serializer = TimedJSONWebSignatureSerializer(dev.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data = serializer.loads(token)
    except BadData:
        return None
    else:
        email = data.get('email')
        user_id = data.get('user_id')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user
